<?php
namespace App\Http\Controllers;
use App\AdminUser;
use App\Customer;
use App\Contact;
use Illuminate\Support\Facades\DB;

class CustomerController extends Controller{
    /**
     * 展示通讯录
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function setting(Customer $customer){
        return view('admin.test.customer',compact('customer'));
    }
    public function index()
    {
//        $users=[];
//        for($i=1;$i<10;$i++)
//        {
//            $users['name']='test'+$i;
//            $users['password']="123456";
//            $users['address']='地址测试'+"'"+$i+"'"+"11";
//            $users['phone']='231321'+"'"+$i+"'";
//            $users['email']='521321'+$i;
//            AdminUser::create($users); //创建字段
//        }
        //print_r($users);die;

        return view('admin.customer.index');

    }
    //避免多次对表查询
    public function Customer(){

    }

    /**
     * 所有客户数据  带测试例子
     */
    public function data()
    {
        return $this->data_fliter("Customer_All");

        date_default_timezone_set("Asia/Shanghai");
        $users=Customer::orderBy('created_at', 'desc')->get();
        $time=$users[0]['next_contact'];
        $time4=date('Y-m-d H:i:s', time());
        $time1=$users[0]['updated_at'];
        //return $time4."更新时间".$time1;
        return round((strtotime($time4)-strtotime($time1))/3600/24);

        $time2=$users[0]['contact_cycle'];
        //return $time;
        //$time1=date(c);
        $d1=strtotime($time1); //上次修改时间
        $d2=strtotime($time); //下次联系时间
        $Days=round(($d2-$d1)/3600/24);
        $Days=$Days % ($time2+1);
        if($Days==0){
            $Days="请今天去联系客户";
        }
        else if($Days==1){
            $Days="请明天去联系客户";
        }else if($Days==2){
            $Days="请后天去联系客户";
        }else{
            $Days="还剩天数:".($time2-$Days);
            //$Days= "time=".$d1."time1=".$d2.'$days='.$Days;
        }
        return $Days;
        //相差时间$days
        //我假设 5天  差值如果=1


        //$users=Customer::orderBy('created_at', 'desc')->with(['user_name','contact_name'])->get();
        //获取关联表中的某个字段值
//        $n=0;
//        foreach($users as  $user)
//        {
//           if($user['user_name']!=null){
//               $users[$n]['user_id']=$user['user_name']['id'];
//           }
//           if($user['contact_name']!=null){
//               $users[$n]['contact_id']=$user['contact_name']['id'];
//           }
//           $n=$n+1;
//        }
//        return $users;
        //以下是分页写法
//        $count=Customer::count();
//        if ($count>0) {
//            if(isset($_GET['key']) && $_GET['key']['key']!="") {
//                $key= $_GET['key']['key'];//搜索序列号
//                $value= $_GET['key']['value'];//搜索序列号
//                if($key!="ID")
//                {
//
//                    $users = Customer::where($key,'like','%'.$value.'%')->get();
//                }
//                else{
//
//                    $users = Customer::where([$key=>$value])->get();
//                }
//            }
//            else{
//                $page = $_GET['page']; //当前页数
//                $limit = $_GET['limit']; //每页的数量
//                $page_count = ($page - 1) * $limit;
//                $users = Customer::orderBy('created_at', 'desc')->with(['user_name','contact_name'])->offset($page_count)->limit($limit)->get();
//            }
//            return json_encode(
//                [
//                    "code" => 0,
//                    'msg' => '',
//                    'count' => $count,
//                    'data' => $users
//                ]);
//        } else{
//            return [
//                'code'=>0,
//                "msg"=>"",
//                "count"=>0,
//                "data"=>[]
//            ];
//        }

    }
    /**
     * 自身客户数据
     */
    public function data2($id){

        return $this->data_fliter('Customer_NotAll',$id);
    }
    /**
     *自身线索数据
     */
    public function data3($id){
        return $this->data_fliter('lead_NotAll',$id);
    }
    /**
     *全部线索数据
     */
    public function data4(){

        $data=$this->data_fliter('lead_All');
        return $data;
    }
    /**
     *联系人数据
     */
    public function data5($id){}
    /**
     * 仍回客户池
     */
    public function customer_roll($id){
        $sql="update customer set user_id=0 where";
        $column="";
        for($i=0;$i<count($_REQUEST);$i++)
        {
            if($i==(count($_REQUEST)-1)){
                $column=$column."id=".$_REQUEST[$i];
            }else{
                $column=$column."id=".$_REQUEST[$i]." "."or"." ";
            }
        }
        $sql=$sql." ".$column;
        DB::select($sql);
        return back();
    }
    /**
     * 客户重分配界面
     */
    public function translation(){
        $users=AdminUser::get();
        return view('admin.customer.customer_translation',compact('users'));
    }
    /**
     * 客户重分配
     */
    public function customer_Redistribution(){
//dd($_REQUEST);
        $sql="UPDATE customers SET user_id=".$_REQUEST['user_id']." where";
        $column="";
        for($i=0;$i<count($_REQUEST['lists']);$i++)
        {
            if($i==(count($_REQUEST['lists'])-1)){
                $column=$column."id=".$_REQUEST['lists'][$i];
            }else{
                $column=$column."id=".$_REQUEST['lists'][$i]." "."or"." ";
            }
        }
        $sql=$sql." ".$column;
        //return $sql;die;

        if (DB::update($sql)>0){
            return back();
        }
    }

    public function contact_create(){
        return view('admin.contact.create');
    }
    public function create(){
        $users=AdminUser::get();
        return view('admin.customer.create',compact('users'));
    }
    //update
    public function view_update(Customer $customer){

        $prov=$_REQUEST['prov'];//省
        $city=$_REQUEST['city'];//市
        $dist=$_REQUEST['dist'];//区
        $address=$prov.$city.$dist;//地址
       // $contact_id=Contact::orderBy('created_at', 'desc')->first()['id'];//获取最新添加的联系人
        $customer->company_address=$address;
        $customer->next_contact=$_REQUEST['next_time'];
        $customer->customer_level=$_REQUEST['customer_level']."星";
        $customer->contact_cycle=$_REQUEST['contact_cycle'];
        //$customer['customer_status']=$data['customer_status'];
        $customer->customer_type=$_REQUEST['customer_type'];
        $customer->company_size=$_REQUEST['company_size'];
        $customer->user_id=$_REQUEST['user_id'];
       // $customer->contact_id=$_REQUEST['contact_id'];
        $customer->save();
        $arr=array();
        $arr['statu']=200;

        return $arr;
    }
    //修改界面
    public function edit(Customer $customer){
        $users=AdminUser::get();
        return view('admin.customer.update',compact('customer','users'));
    }
    /**
     * 添加操作逻辑简单实现
     */
    public function store(){
        $data=$_REQUEST;

        $customer=array();
        $contact=array();
        $prov=$data['prov'];//省
        $city=$data['city'];//市
        $dist=$data['dist'];//区
        $contact['source']=$data['source'];
        $contact['name']=$data['name'];
        $contact['company_name']=$data['company_name'];
        $contact['position']=$data['position'];
        if($data['gender']=='先生')
        {
            $contact['gender']='男';
        }else{
            $contact['gender']='女';
        }
        $address=$prov.$city.$dist;//地址
        $contact['address']=$address;
        $contact['phone']=$data['phone'];
        $contact['email']=$data['email'];
        //$contact['remark']=$data['remark'];
        $contact['next_time']=$data['next_time'];
        $contact['is_lead'] =1;//是否有人负责
        $contact['is_customer'] =1; //是否为客户
        $contact['user_id']=$data['user_id'];
        Contact::create($contact);
        $contact_id=Contact::orderBy('created_at', 'desc')->first()['id'];//获取最新添加的联系人
        $customer['company_address']=$address;
        $customer['next_contact']=$data['next_time'];
        $customer['customer_level']=$data['customer_level']."星";
        $customer['contact_cycle']=$data['contact_cycle'];
       //$customer['customer_status']=$data['customer_status'];
        $customer['customer_type']=$data['customer_type'];
        $customer['company_size']=$data['customer_size'];
        $customer['user_id']=$data['user_id'];
        $customer['contact_id']=$contact_id;

        Customer::create($customer); //创建字段
        //渲染
        $arr=array();
        $arr['statu']=200;

        return $arr;
       // return redirect('/admin/customer');
    }
    /*
     * 删除
     */
    public function delete($id)
    {
        Customer::where('id', '=', $id)->delete();
        return back();
    }
    ///备用批量删除手法
    public function DeleteAll($data){
        switch(count($data))
        {
            case 1:AdminUser::whereIn('id',[$data[0]])->delete();break;
            case 2:AdminUser::whereIn('id',[$data[0],$data[1]])->delete();break;
            case 3:AdminUser::whereIn('id',[$data[0],$data[1],$data[2]])->delete();break;
            case 4:AdminUser::whereIn('id',[$data[0],$data[1],$data[2],$data[3]])->delete();break;
            case 5:AdminUser::whereIn('id',[$data[0],$data[1],$data[2],$data[3],$data[4]])->delete();break;
            case 6:AdminUser::whereIn('id',[$data[0],$data[1],$data[2],$data[3],$data[4],$data[5]])->delete();break;
            case 7:AdminUser::whereIn('id',[$data[0],$data[1],$data[2],$data[3],$data[4],$data[5],$data[6]])->delete();break;
            case 8:AdminUser::whereIn('id',[$data[0],$data[1],$data[2],$data[3],$data[4],$data[5],$data[6],$data[7]])->delete();break;
            case 9:AdminUser::whereIn('id',[$data[0],$data[1],$data[2],$data[3],$data[4],$data[5],$data[6],$data[7],$data[8]])->delete();break;
            case 10:AdminUser::whereIn('id',[$data[0],$data[1],$data[2],$data[3],$data[4],$data[5],$data[6],$data[7],$data[8],$data[9]])->delete();break;
        }
    }
    public function del(){
        $sql="delete from customers where";
        $column="";
        for($i=0;$i<count($_REQUEST);$i++)
        {
            if($i==(count($_REQUEST)-1)){
                $column=$column."id=".$_REQUEST[$i];
            }else{
                $column=$column."id=".$_REQUEST[$i]." "."or"." ";
            }
        }
        $sql=$sql." ".$column;
        DB::select($sql);
        return back();
        //return


       // $this->DeleteAll( $_REQUEST); //另类删除手法

        //AdminUser::whereIn('id',$bb)->get();

        ///AdminUser::where
    }
    public function update(){
        //print_r(json_decode($_REQUEST),true)
        //$data=json_decode($_REQUEST,true);
      $filds=$this->array_hebing('customer_level','customer_type','company_size','contact_cycle');//传入需要更新的字段

      if(empty($filds))  //判断数据是否为空 是则不修改
      {
          return ['statu'=>'0'];
      }
      else{

          //print_r($_REQUEST);

          Customer::where('id', $_REQUEST['id'])->update($filds);
          return ['statu'=>'200'];
      }
    }
    /**
     * @param $type
     *  //$type=Customer_All 代表所有客户
    //$type=Customer_NotAll 代表自身客户
     *  //$type=lead_All 代表所有线索
    //$type=lead_NotAll 代表自身线索
     * @param null $id
     * @return array|string
     */
    public function data_fliter($type,$id=null){

        $count=0;  //展示的数据总数
        $users=[]; //展示的数据

        switch ($type){
            case "Customer_All":  $count=Customer::count();break;
            case "Customer_NotAll":$count=Customer::where('user_id','=',$id)->count();break;
            case "lead_All":$count=Contact::where('is_customer','=','0')->where('is_lead','=','0')->count();break;
            case "lead_NotAll":$count=Contact::where('is_customer','=','0')->where('is_lead','=','1')->where('user_id','=',$id)->count();break;
        }

        //
        if ($count>0) {
            if(isset($_GET['key']) && $_GET['key']['key']!="") {
                $key= $_GET['key']['key'];//搜索序列号
                $value= $_GET['key']['value'];//搜索序列号
                $users = Customer::where($key,'like','%'.$value.'%')->get();
            }
            else{
                $page = $_GET['page']; //当前页数
                $limit = $_GET['limit']; //每页的数量
                $page_count = ($page - 1) * $limit;
                switch ($type){
                    case "Customer_All":
                        //数据逻辑
                        $users = Customer::orderBy('created_at', 'desc')->offset($page_count)->limit($limit)->get();
                        //剩余时间操作
                        $n=0;
                        foreach($users as $a1)
                        {
                            if($a1['contact_status']==0){ //如果联系状态 0=未完成 1=完成 2=延期
                                date_default_timezone_set("Asia/Shanghai");
                                $time=$a1['next_contact'];
                                $time4=date('Y-m-d H:i:s', time());
                                $sjc=round((strtotime($time)-strtotime($time4))/3600/24);
                                $time_left="";
                                //return $time4."更新时间".$time1;
                                if($sjc==0){
                                    $time_left="该联系咯";
                                }
                                else if($sjc==1){
                                    $time_left="明天就该联系咯";
                                }else if($sjc==2)
                                {
                                    $time_left="后天就该联系咯";
                                }else if($sjc<=0){

                                    $time_left="已延期".abs($sjc).'天';
                                }
                                else{
                                    $time_left="还剩".$sjc."天";
                                }


                            }
//                            //剩余时间
//                            $time_left=$a1['next_contact']-time();
                            $users[$n]['time_left']=$time_left;
                            $n=$n+1;
                        };
                        break;
                    case "Customer_NotAll":
                        $users=Customer::orderBy('created_at','desc')->where('user_id','=',$id)->offset($page_count)->limit($limit)->get();
                        $n=0;
                        foreach($users as $a1)
                        {
                            if($a1['contact_status']==0){ //如果联系状态 0=未完成 1=完成 2=延期
                                date_default_timezone_set("Asia/Shanghai");
                                $time=$a1['next_contact'];
                                $time4=date('Y-m-d H:i:s', time());
                                $sjc=round((strtotime($time)-strtotime($time4))/3600/24);
                                $time_left="";
                                //return $time4."更新时间".$time1;
                                if($sjc==0){
                                    $time_left="该联系咯";
                                }
                                else if($sjc==1){
                                    $time_left="明天就该联系咯";
                                }else if($sjc==2)
                                {
                                    $time_left="后天就该联系咯";
                                }else if($sjc<=0){

                                    $time_left="已延期".abs($sjc).'天';
                                }
                                else{
                                    $time_left="还剩".$sjc."天";
                                }
                            }
//                            //剩余时间
//                            $time_left=$a1['next_contact']-time();
                            $users[$n]['time_left']=$time_left;
                            $n=$n+1;
                        };
                        break;
                    case "lead_All":$users=Contact::orderBy('created_at', 'desc')->where('is_customer','=','0')->where('is_lead','=','0')->with('user_name')->offset($page_count)->limit($limit)->get();
                        $n=0;
                        foreach($users as $a1)
                        {
                            $users[$n]['user_name1']=$a1['user_name']->name;
                            $n=$n+1;
                        };break;
                    case "lead_NotAll":$users=Contact::orderBy('created_at', 'desc')->where('is_customer','=','0')->where('is_lead','=','1')->where('user_id','=',$id)->with('user_name')->offset($page_count)->limit($limit)->get();
                        $n=0;
                        foreach($users as $a1)
                        {
                            $users[$n]['user_name1']=$a1['user_name']->name;
                            $n=$n+1;
                        };break;
                }
                //$users = Customer::orderBy('created_at', 'desc')->where('is_customer','=','1')->offset($page_count)->limit($limit)->get();
            }
            return json_encode(
                [
                    "code" => 0,
                    'msg' => '',
                    'count' => $count,
                    'data' => $users
                ]
            );
        } else{
            return [
                'code'=>0,
                "msg"=>"",
                "count"=>0,
                "data"=>[]
            ];
        }
    }
    /**
     * //组成一个我所要的数组用于数据库更新 并且
     * @param array ...$numbers 传进去的字段
     * @return array /￥/返回一个键=字段 值=数值的数组
     */
    public function array_hebing(...$numbers){
        $data=Customer::where('id', $_REQUEST['id'])->first();;
        $filds=[];
        if($_REQUEST && is_array($_REQUEST)){   //组成一个我所要的数组用于数据库更新
            //print_r($_REQUEST);die;
            foreach($numbers as $fild){
                foreach ($_REQUEST as $key=> $value){
                    if($fild==$key)
                    {
                            $filds[$fild] = $value;
                            continue;
                    }
                }
            }
            $start=0;  //循环记数
            foreach($filds as $key=>$value)  //删除请求更新字段中没有修改的字段
            {
                if($data[$key]==$filds[$key]) {   //判断是否相同 相同则从需要更新的数组中删除该键值
                        array_splice($filds, $start, 1);
                        $start=$start-1;
                }
                $start=$start+1;
            }
        }
        return $filds;
    }
}